package spring.boot.btc.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spring.boot.btc.common.BlockLastLock;
import spring.boot.btc.common.BlockProperty;
import spring.boot.btc.model.Block;

/**
 * 区块链操作
 */
@Slf4j
@Service
public class BlockService {

    @Autowired
    private BlockSenderService blockSenderService;

    /**
     * 新的区块添加到最后
     *
     * @param block 新的区块
     * @param type  1=自己挖矿  2=接收到广播
     */
    public void addToLast(Block block, int type) {
        synchronized (BlockLastLock.LOCK) {
            Block lastBlock = BlockProperty.getLast();
            if (block.getPreHash().equals(lastBlock.getHash()) && block.getVersion() - lastBlock.getVersion() == 1) {
                BlockProperty.blockList.add(block);
                if (type == 1) {
                    log.info("添加到区块末尾成功！挖矿有效！");
                    JSONObject json = new JSONObject();
                    json.put("type", 1);
                    json.put("msg", block);
                    blockSenderService.send(json.toJSONString());
                } else {
                    log.info("添加到区块末尾成功！广播接收到的区块数据有效！");
                }
            } else {
                if (type == 1) {
                    log.info("添加到区块末尾失败！挖矿计算比别人慢了，再接再厉！");
                } else {
                    log.info("添加到区块末尾失败！广播接收到的数据过时了！");
                }
            }
        }
    }

}
